package com.block.api.interceptor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.api.reqbean.ReqBeanUtil;
import com.block.common.encrypt.factory.EncryptFactory;
import com.block.common.model.dto.EncryptKeyDTO;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.common.sign.factory.SignFactory;
import com.block.common.util.HttpReturnUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.ChannelInfo;
import com.block.db.entity.SourceBaseInfo;
import com.block.source.service.ISourceBaseInfoService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;


/**
 * 导单
 */
public class InitSourceInterceptor implements HandlerInterceptor {

	private static final Logger log = LogFactory.getSourceLog();

	@Autowired
	ISourceBaseInfoService sourceBaseInfoService;
	@Autowired
	IApplicationInfoService applicationInfoService;
	@Autowired
	IChannelCommonService channelCommonService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String uri = request.getRequestURI();
		String reqIp = ServletUtil.getClientIP(request);
		try {

			String paramContent = IoUtil.read(request.getInputStream(), Charset.defaultCharset());
			log.info("【数据导入】【请求地址】{}【请求参数】{}", uri, paramContent);

			// TODO: 2023/5/21 请求参数校验

			JSONObject jsonObject = JSON.parseObject(paramContent);
			String appCode = jsonObject.getString("appCode");
			String requestNo = jsonObject.getString("requestNo");

			SourceBaseInfo sourceBaseInfo = sourceBaseInfoService.getSourceInfo(appCode);
			if (ObjectUtil.isEmpty(sourceBaseInfo)){
				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("渠道信息为空"));
				return false;
			}
			if (ObjectUtil.equal(sourceBaseInfo.getStatus(), Integer.valueOf(0))){
				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("渠道状态不可用"));
				return false;
			}

			EncryptKeyDTO sourceKeyDTO = new EncryptKeyDTO();
			sourceKeyDTO.setAppCode(sourceBaseInfo.getChannelCode());
			sourceKeyDTO.setAppKey(sourceBaseInfo.getAppKey());
			sourceKeyDTO.setAppSecret(sourceBaseInfo.getAppSecret());
			sourceKeyDTO.setPubKey(sourceBaseInfo.getPubKey());
			sourceKeyDTO.setPriKey(sourceBaseInfo.getPriKey());

			// 请求验签
//			boolean verifyResult = SignFactory.getService(sourceBaseInfo.getSignType()).verifySign(sourceKeyDTO, jsonObject);
//			if (!verifyResult){
//				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("验签失败"));
//				return false;
//			}

			//业务参数 解密
			JSONObject tranData = null;
			try {
				tranData = EncryptFactory.getService(sourceBaseInfo.getEncryptType()).decryptTranData(sourceKeyDTO, jsonObject);
				log.info("【数据导入】【揭秘完数据】{}", JSON.toJSONString(tranData));
			}catch (Exception exception){
				exception.printStackTrace();
				HttpReturnUtil.returnJson(response, requestNo, ResultInfoVO.error("业务参数解密失败"));
				return false;
			}

			ChannelInfo channelInfo = channelCommonService.getChannelInfoCache(sourceBaseInfo.getChannelCode());
			ApplicationInfo applicationInfo =applicationInfoService.getAppInfoByType(channelInfo.getAppType());

			request.setAttribute("tranDataBean", tranData.toJavaObject(ReqBeanUtil.getBeanClass(uri)));
			request.setAttribute("tranData", tranData);
			request.setAttribute("requestNo", requestNo);
			request.setAttribute("sourceBaseInfo", sourceBaseInfo);
			request.setAttribute("channelInfo", channelInfo);
			request.setAttribute("applicationInfo", applicationInfo);
			request.setAttribute("uri", uri);
			request.setAttribute("ip", reqIp);

			return  true;
		} catch (Exception e){
			log.error("拦截器处理异常json...",e);
			HttpReturnUtil.returnJson(response, ResultInfoVO.error("请求处理异常：" + e.getMessage()));
			return  false;
		}
	}

}
